global root_dir = "`1'"

include "$root_dir/code/config/config.do"

cap noi log using ${log_dir}/Table_A31_shocklevel_balance.log, replace name(tabl)

capture noi { 

    * Falsification test / shock balance
    * Tests plausibility of assumption 3 (conditional quasi-random shock assignment)

    * ------------------------------------
    * a) build country-level data
    * ------------------------------------

    * Load firm level data, define RHS variables, and fixed effects
    use ${final_dir}/regression_dataset_from1970_tfacit1_avglog.dta, clear
    local macro_controls GDPGAP VAEMP GDPPC mds_control mshare manufsize offshoring spilloversownpw spilloversotherpw 
    local F lse_id
    local F_IY lse_id yearindustry
    local F_IY_CY lse_id yearindustry yearctry
    local stocks stockown stockownzero stockother stockotherzero
    local spillovers spilloversown_og spilloversownzero_og spilloversother_og spilloversotherzero_og

    * Define control and FE specifications to residualize
    local ct1 
    local fe1 
    local ct2 
    local fe2 `F_IY'
    local ct3 
    local fe3 `F_IY_CY'
    local ct4 `spillovers' `stocks'
    local fe4 `F_IY_CY'

    * Residualize and take s_n-weighted country-year mean
    ssaggregate auto95_bia LSW HSW `macro_controls', /// 
        n(country) t(year) s(s_nt) sfilename(${dataset_dir}/bhj/lseid_year_ctryweights_long.dta) l(lse_id) ///
        controls("`ct1'" "`ct2'" "`ct3'" "`ct4'") ///
        absorb("`fe1'" "`fe2'" "`fe3'" "`fe4'")

    foreach v of local macro_controls {
        ren `v'* z`v'*
    }
    ren LSW* zLSW*
    ren HSW* zHSW*
    forvalues r = 1/4 {  
            gen zISP`r' = zLSW`r' - zHSW`r'
    }
    mmerge country year using  ${dataset_dir}/bhj/country_year_macrovariables.dta, unmatched(master)
    drop _m
    egen country_id = group(country)
    xtset country_id year

    * ------------------------------------
    * b) run regressions, output table
    * ------------------------------------

    texdoc init ${tab_dir}/appendix/Table_A31_shocklevel_balance.tex, replace
    texdoc stlog, nolog

    *why do we need a manual program here? does ivreg2 not provide that functionality?
    cap prog drop makestar
    program define makestar, rclass
        if `1'<= 0.01 {
            local star "***"
        }
        else if `1'<=0.05{
            local star "**"
        }
        else if `1'<=0.1{
            local star "*"
        }
        else {
            local star ""
        }
        return local star `star'
    end


    * b.1) Panel A: Countrylevel balance:  Skillpremium, residualized on SS FIY CY
    estimates clear
    foreach v in GDPGAP VAEMP GDPPC manufsize mds_control offshoring spilloversownpw spilloversotherpw { 
        ivreg2 z`v'4 (zISP4 = gISP) [aw = s_n], cluster(country)
        ereturn display
        local se : di %10.2f r(table)[2,1]
        local b : di %10.2f r(table)[1,1]
        local p = r(table)[4,1]
        di "se: `se'"
        di "coef: `b'"
        di "p: `p'"
        makestar `p'
        local star `r(star)'
        di "`star'"
        texdoc local cof_`v' = "`b'" + "\sym{" + "`star'" + "}"
        sleep 500
        texdoc local se_`v' : di %10.2f `se'
        sleep 500
    }

    texdoc local show_pvalues_note yes
    texdoc local notes "This table reports coefficients from separate regressions of country-level observables on the log inverse skill premium. The respective independent variables are residualized on firm, industry-year, and country-year fixed effects. Standard errors are reported in Column 2 and clustered at the country-level."
    texdoc stlog close
    qui include ${code_dir}/config/texdoctools.do
    tex `texpreamble'

    /*tex
    \begin{tabular}{@{}l*{2}S@{}}
    \toprule

    & \mc{Estimate} & \mc{(SE)} \\
    & \mc{(1)} & \mc{(2)} \\
    \midrule

    \noalign{\medskip}
    \nsk GDP Gap                     &   `cof_GDPGAP'  &   (`se_GDPGAP')     \\
    \nsk Labor Productivity   &   `cof_VAEMP'  &   (`se_VAEMP')     \\
    \nsk GDP per capita  &   `cof_GDPPC'  &   (`se_GDPPC')     \\
    \nsk Manufacturing size  &   `cof_manufsize'  &   (`se_manufsize')     \\
    \nsk \mrmc{Manufacturing size \\ (low-skill weighted)} & `cof_mds_control' & (`se_mds_control') \\
    \nsk Offshoring   &   `cof_offshoring'  &   (`se_offshoring')     \\
    \nsk Recent auto95 innovation &   `cof_spilloversownpw'  &   (`se_spilloversownpw')     \\
    \nsk Recent other innovation  &   `cof_spilloversotherpw'  &   (`se_spilloversotherpw')     \\

    \noalign{\medskip}
    Stocks and spillovers & {\text{Yes}} & {\text{Yes}}\\
    Fixed effects & {\text{F+IY+CY}} & {\text{F+IY+CY}} \\
    Number of country-years & {\text{615}}  & {\text{615}}  \\

    \bottomrule
    \end{tabular}

    tex*/
    tex `texpostamble'
    texdoc close

}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}